package com.probiz.estore.core.security;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.ui.AccessDeniedHandlerImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.system.service.AppMenuManager;

public class ProbizAccessDeniedHandlerImpl extends AccessDeniedHandlerImpl {
    //~ Static fields/initializers =====================================================================================

    public static final String ACEGI_SECURITY_ACCESS_DENIED_EXCEPTION_KEY = "ACEGI_SECURITY_403_EXCEPTION";
    protected static final Log logger = LogFactory.getLog(AccessDeniedHandlerImpl.class);

    //~ Instance fields ================================================================================================
    private AppMenuManager appMenuManager = null;
    private String errorPage;

    //~ Methods ========================================================================================================

    public void handle(ServletRequest request, ServletResponse response, AccessDeniedException accessDeniedException)
        throws IOException, ServletException {
//    	HttpServletRequest request_ = (HttpServletRequest)request;
//    	//System.out.println("aaaa-="+request_.getRequestURI());
//    	//查找当前模块下第一个拥有权限的页面并跳转
//    	Pattern p = Pattern.compile("/StoreAdmin/(.*?)/.*?");
//		Matcher m = p.matcher(request_.getRequestURI());
//		if(m.find()&&m.groupCount()==1){
//			GrantedAuthority[] recipents = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
//			if(recipents.length>0){
//				StringBuffer sb = new StringBuffer("");
//				for(GrantedAuthority ga:recipents){
//					sb.append("or ar.roleName = '"+ga.getAuthority()+"' ");
//				}
//				String hql = "select distinct am from AppMenu am left join fetch am.appRoles ar where am.appMenu.appMenu.menuName=? ";
//				List<AppMenu> menus = appMenuManager.findByHql(hql+" and ("+sb.substring(3)+") order by am.sortOrder asc", m.group(1));
//				if(!menus.isEmpty()){
//					System.out.println("/StoreAdmin"+menus.get(0).getUrl());
//			    	HttpServletResponse response_ = (HttpServletResponse)response;
//					response_.sendRedirect("/StoreAdmin"+menus.get(0).getUrl());
//					return ;
//				}
//			}
//		}
    	//response_.sendRedirect("/StoreAdmin/diner/dinerVenue.html");
        if (errorPage != null) {
            // Put exception into request scope (perhaps of use to a view)
            ((HttpServletRequest) request).setAttribute(ACEGI_SECURITY_ACCESS_DENIED_EXCEPTION_KEY, accessDeniedException);

            // Perform RequestDispatcher "forward"
            RequestDispatcher rd = request.getRequestDispatcher(errorPage);
            rd.forward(request, response);
        }

        if (!response.isCommitted()) {
            // Send 403 (we do this after response has been written)
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        }
    }

    /**
     * The error page to use. Must begin with a "/" and is interpreted relative to the current context root.
     *
     * @param errorPage the dispatcher path to display
     *
     * @throws IllegalArgumentException if the argument doesn't comply with the above limitations
     */
    public void setErrorPage(String errorPage) {
        if ((errorPage != null) && !errorPage.startsWith("/")) {
            throw new IllegalArgumentException("ErrorPage must begin with '/'");
        }

        this.errorPage = errorPage;
    }

	public void setAppMenuManager(AppMenuManager appMenuManager) {
		this.appMenuManager = appMenuManager;
	}
    
}
